package com.huifaapp.mall.activity;


import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.design.widget.TabLayout;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.ProgressBar;
import android.widget.TextView;
import android.widget.Toast;


import com.blankj.utilcode.util.FileIOUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ToastUtils;
import com.bumptech.glide.Glide;
import com.bumptech.glide.request.FutureTarget;
import com.google.gson.Gson;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huifaapp.mall.APP;
import com.huifaapp.mall.R;
import com.huifaapp.mall.adapter.TabLayoutFragmentListviewAdapter;
import com.huifaapp.mall.afinal.SPConstants;
import com.huifaapp.mall.api.ApiManager;
import com.huifaapp.mall.api.ObserverCallback;
import com.huifaapp.mall.bean.MinuteKillGetSpecialTime;
import com.huifaapp.mall.bean.Minutekillshop;
import com.huifaapp.mall.bean.ShareImageBean;
import com.huifaapp.mall.bean.SpecialAdvert;
import com.huifaapp.mall.dialogs.LoadingDialog;
import com.huifaapp.mall.uitils.AUniqueIdentifier;
import com.huifaapp.mall.uitils.Contig;
import com.huifaapp.mall.uitils.ShareUtils;
import com.huifaapp.mall.uitils.UtilsImage;
import com.squareup.okhttp.Request;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import java.io.File;
import java.io.FileInputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;

import io.reactivex.Observable;
import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.disposables.Disposable;
import io.reactivex.functions.Function;
import io.reactivex.schedulers.Schedulers;

import static com.huifaapp.mall.afinal.Constants.savePath;

/**
 * Created by Administrator on 2017/12/22.
 */

public class MinuteKillActivity extends AppCompatActivity {


    private TabLayout tablayout;
    private ViewPager viewpager;
    private TabAdapter adapter;
    private List<Fragment> fragments = new ArrayList<>();
    public static final ArrayList<String> tabs1 = new ArrayList<String>(); //标签名称
    private List<Integer> tabNumbers1 = new ArrayList<>(); //信息数目
    List<Integer> tabIstime1 = new ArrayList<>(); //信息数目
    ArrayList<String> id=new ArrayList<>();
    private ViewHolder holder;
    public static String MinuteKillId;
    private PullToRefreshListView mylv_tablayout;
    private ImageView fragment_viewpager,fragment_viewpager1,fragment_viewpager2;
    private LinearLayout ll_fragment_viewpager;
    Minutekillshop listshop;
    TabLayoutFragmentListviewAdapter adapterlv;
    private ProgressBar progressBarHorizontal;
    private ImageView iv_minutekill_back;
    public static Map<Integer, Boolean> hmap;
    private ImageView iv_share_minute;
    ArrayList<String> idlist=new ArrayList<>();
    private static final int SHARET_WXHY = 517;
    List<Minutekillshop.DataBean.ListBean> listb;
    private int Isspceial;
     int a=0;
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_minute_kill);

        hmap = new HashMap<>();
        viewpager = (ViewPager) findViewById(R.id.vp_view_minute_kill);
        tablayout = (TabLayout) findViewById(R.id.tab_minute_tabs);
        mylv_tablayout= (PullToRefreshListView) findViewById(R.id.mylv_tablayout);
        fragment_viewpager= (ImageView) findViewById(R.id.fragment_viewpager);
        fragment_viewpager1= (ImageView)findViewById(R.id.fragment_viewpager1);
        fragment_viewpager2= (ImageView) findViewById(R.id.fragment_viewpager2);
        ll_fragment_viewpager= (LinearLayout) findViewById(R.id.ll_fragment_viewpager);
        iv_minutekill_back= (ImageView) findViewById(R.id.iv_minutekill_back);
        iv_share_minute= (ImageView) findViewById(R.id.iv_share_minute);
        iv_minutekill_back.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                tabs1.clear();
                finish();

            }
        });

        Intent intent=getIntent();
        String type = intent.getStringExtra("type");
        String id=intent.getStringExtra("id");
        loadtabs();

        loadtabsfragment();
        Log.e("数据","是否是云店主"+SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE));
        if(SPUtils.getInstance().getString(SPConstants.KEY_ISSTORE).equals("1")){
            iv_share_minute.setVisibility(View.VISIBLE);
        }else{
            iv_share_minute.setVisibility(View.GONE);
        }
        iv_share_minute.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Log.e("数据Toady", Contig.checkedIndexminutekill + "-=====Contig.checkedIndex===id");
                if (Contig.checkedIndexminutekill.size() == 0) {
                    Toast.makeText(MinuteKillActivity.this, "没有选择，请选择再分享！", Toast.LENGTH_SHORT).show();
                } else {
                    for (int i = 0; i < Contig.checkedIndexminutekill.size(); i++)
                        idlist.add(listb.get(Contig.checkedIndexminutekill.get(i)).getId());
                    Log.e("数据Toady", idlist + "-===========id");
                    StringBuffer permission = new StringBuffer();
                    for (int i = 0; i < idlist.size(); i++) {
                        if (i == 0) {
                            permission.append(idlist.get(i));
                        } else {
                            permission.append("," + idlist.get(i));
                        }

                    }

                    ApiManager
                            .getInstance()
                            .getApiServer()
                            .getShareImage(SPUtils.getInstance().getString(SPConstants.KEY_USER_TOKEN), AUniqueIdentifier.getDeviceId(MinuteKillActivity.this), permission.toString())
                            .compose(ApiManager.<ShareImageBean>handlResult())
                            .subscribe(new ObserverCallback<ShareImageBean>(MinuteKillActivity.this) {
                                @Override
                                protected void onSuccessful(ShareImageBean resp) {

                                    saveImage(resp.getPoster(), resp.getFailure(), SHARET_WXHY);

                                }

                                @Override
                                protected void onError(String code, String errMsg) {
                                    ToastUtils.showShortSafe(errMsg);
                                }
                            });

                    idlist.clear();
                }
            }
        });
    }
    private void saveImage(List<String> imageUrls, final String cconten, final int type) {

        Log.v("shiran","------------saveImage------------");

        final LoadingDialog dialog = new LoadingDialog(MinuteKillActivity.this);
        dialog.setContent("正在生成图片请稍后");


        Observable.just(imageUrls)
                .map(new Function<List<String>, List<String>>() {

                    @Override
                    public List<String> apply(List<String> list) throws Exception {

                        List<String> paths = new ArrayList<String>();
                        for (String s : list) {
                            FutureTarget<File> future = Glide.with(APP.getInstance())
                                    .load(s)
                                    .downloadOnly(500, 500);
                            File cacheFile = future.get();
                            String uuid = UUID.randomUUID().toString();
                            FileIOUtils.writeFileFromIS(savePath + uuid + ".jpg", new FileInputStream(cacheFile));
                            String pat = savePath + uuid + ".jpg";
                            paths.add(pat);

                        }


                        return paths;
                    }
                }).subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<List<String>>() {
                    @Override
                    public void onSubscribe(Disposable d) {
                        if (dialog != null && !dialog.isShowing()) {
                            dialog.show();
                        }
                    }

                    @Override
                    public void onNext(List<String> value) {
                        LogUtils.e(value);
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }

                        switch (type) {
                            case SHARET_WXHY:

                                ShareUtils.sharePicToFriendNoSDK(MinuteKillActivity.this, value);
//                                        ClipboardUtils.copyText(cconten);
//                                        ToastUtils.showShortSafe("内容已复制!");
                                break;
//                            case SHARET_WXPYQ:
//                                ShareUtils.share9PicsToWXCircle(getActivity(), "", value);
//                                break;
                            default:

                                break;
                        }

                    }

                    @Override
                    public void onError(Throwable e) {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }

                    @Override
                    public void onComplete() {
                        if (dialog != null && dialog.isShowing()) {
                            dialog.dismiss();
                            dialog.cancel();
                        }
                    }
                });

    }

    @Override
    public void onBackPressed() {
        super.onBackPressed();
        tabs1.clear();
    }

    private void loadtabsfragment(){
        OkHttpUtils.get().url(ApiManager.ZT_SPECIAL_ADVERT+"?address="+Contig.typex).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }
            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                SpecialAdvert list = gson.fromJson(response,SpecialAdvert.class);
                if(list.getCode().equals("10000")) {
                    if(list.getData().getList().size()==1){
                        fragment_viewpager.setVisibility(View.VISIBLE);
                        ll_fragment_viewpager.setVisibility(View.GONE);
                        UtilsImage.uploadimageview(fragment_viewpager,list.getData().getList().get(0).getImg(),null,MinuteKillActivity.this);
                    }else{
                        fragment_viewpager.setVisibility(View.GONE);
                        ll_fragment_viewpager.setVisibility(View.VISIBLE);
                        UtilsImage.uploadimageview(fragment_viewpager1,list.getData().getList().get(0).getImg(),null,MinuteKillActivity.this);
                        UtilsImage.uploadimageview(fragment_viewpager2,list.getData().getList().get(1).getImg(),null,MinuteKillActivity.this);
                    }
                }else{
                    Toast.makeText(MinuteKillActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }
        });
    }


    private void loadtabs(){

        Log.e("特卖",ApiManager.ZT_SPECIAL_GETSPECIALTIME+"?spuPlatform="+Contig.typex);
        OkHttpUtils.get().url(ApiManager.ZT_SPECIAL_GETSPECIALTIME+"?spuPlatform="+Contig.typex).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                Gson gson = new Gson();
                MinuteKillGetSpecialTime list = gson.fromJson(response,MinuteKillGetSpecialTime.class);
                if(list.getCode().equals("10000")) {
                for(int i=0;i<list.getData().size();i++){
                    try{
                    String b=list.getData().get(i).getSpecialTime().substring(11, 16);
                        Integer isSpecial=list.getData().get(i).getIsSpecial();
                        Integer isTimeOver=list.getData().get(i).getIsTimeOver();
                        String ids=list.getData().get(i).getId();
                        id.add(ids);
                        Log.e("数据M",id+"");
                        tabs1.add(b);
                        tabNumbers1.add(isSpecial);
                        tabIstime1.add(isTimeOver);
                    }catch (Exception e){
                        Log.e("",e.getMessage());
                    }

                }

                initviews(tabs1,tabNumbers1,tabIstime1);
                setTabView(tabs1,tabNumbers1,tabIstime1);
                    for (int i = 0; i<tabNumbers1.size(); i++){
                        if(tabNumbers1.get(i)==1){
                            loadshoping(0,a,id.get(i),1);
                            final String k=id.get(i);
                            mylv_tablayout.setMode(PullToRefreshBase.Mode.BOTH);//两端刷新
                            mylv_tablayout.setSelected(true);
                            mylv_tablayout.setScrollingWhileRefreshingEnabled(true);
                            mylv_tablayout.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                                @Override
                                public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                                    loadshoping(0,a,k,1);

                                }

                                @Override
                                public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                                    loadshoping(0,a++,k,1);

                                }
                            });
                            new Handler(new Handler.Callback() {
                                @Override
                                public boolean handleMessage(Message msg) {
                                    mylv_tablayout.setRefreshing(true);
                                    return false;
                                }
                            }).sendEmptyMessageDelayed(0, 200);
                        }else{
                            loadshoping(0,a,id.get(0),tabNumbers1.get(0));
                            mylv_tablayout.setMode(PullToRefreshBase.Mode.BOTH);//两端刷新
                            mylv_tablayout.setSelected(true);
                            mylv_tablayout.setScrollingWhileRefreshingEnabled(true);
                            mylv_tablayout.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                                @Override
                                public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                                    loadshoping(0,a,id.get(0),tabNumbers1.get(0));

                                }

                                @Override
                                public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
                                    loadshoping(0,a++,id.get(0),tabNumbers1.get(0));

                                }
                            });
                            new Handler(new Handler.Callback() {
                                @Override
                                public boolean handleMessage(Message msg) {
                                    mylv_tablayout.setRefreshing(true);
                                    return false;
                                }
                            }).sendEmptyMessageDelayed(0, 200);
                        }
                    }

                }else{
                    Toast.makeText(MinuteKillActivity.this,list.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }


        });
    }
    private void initviews(ArrayList<String> tabs, List<Integer> tabNumbers, List<Integer> tabIstime) {

        List<Fragment> fragments = new ArrayList<>();

        for (int i = 0; i < tabs.size(); i++) {
            Log.e("数据","tsbs============"+tabs);

//         fragments.add(new TabLayoutFragment(this,tabs.get(i)));
           fragments.add(TabLayoutFragment.newInstance(i + 1,MinuteKillId));
        }
        adapter = new TabAdapter(getSupportFragmentManager(), fragments);
        //给ViewPager设置适配器
        viewpager.setAdapter(adapter);
        //将TabLayout和ViewPager关联起来。
        tablayout.setupWithViewPager(viewpager);
        //设置可以滑动
        tablayout.setTabMode(TabLayout.MODE_SCROLLABLE);
    }

    /**
     * 设置Tab的样式
     */
    private void setTabView(ArrayList<String> tabs, final List<Integer> tabNumbers, final List<Integer> tabIstime) {
        holder = null;
        for (int i = 0; i < tabs.size(); i++) {
            //依次获取标签
            TabLayout.Tab tab = tablayout.getTabAt(i);
            //为每个标签设置布局
            tab.setCustomView(R.layout.tab_minutekill_item);
            holder = new ViewHolder(tab.getCustomView());
            //为标签填充数据
            holder.tvTabName.setText(tabs.get(i));
            try {
                if (tabNumbers.get(i) == 0) {
//                    if (tabIstime.get(i) == 1) {
//                        holder.tvTabNumber.setText("已开抢");
//                        Isspceial=01;
//                    } else if (tabIstime.get(i) == 0) {
//                        holder.tvTabNumber.setText("已结束");
//                        Isspceial=00;
//                    } else {
                        holder.tvTabNumber.setText("已开抢");
                        Isspceial=01;
//                    }
                } else if (tabNumbers.get(i) == 1) {
                    holder.tvTabNumber.setText("特卖中");
                    Isspceial=10;
                } else if (tabNumbers.get(i) == 2) {
                    holder.tvTabNumber.setText("即将开始");
                    Isspceial=20;
                }

                //默认选择第一项
//            if (i == 0){
//                holder.tvTabName.setSelected(true);
//                holder.tvTabNumber.setSelected(true);
//                holder.tvTabName.setTextSize(18);
//                holder.tvTabNumber.setTextSize(18);
//                holder.tvTabNumber.setText("特卖中");
//            }

                if (tabNumbers.get(i) == 1) {
                    holder.tvTabName.setSelected(true);
                    holder.tvTabNumber.setSelected(true);
                    holder.tvTabName.setTextSize(17);
                    holder.tvTabNumber.setTextSize(11);
                    viewpager.setCurrentItem(tab.getPosition());
                    MinuteKillId = id.get(tab.getPosition());
                } else {
                    holder.tvTabName.setSelected(false);
                    holder.tvTabNumber.setSelected(false);
                    //恢复为默认字体大小
                    holder.tvTabName.setTextSize(17);
                    holder.tvTabNumber.setTextSize(11);
                }
            }catch (Exception e){
                Log.e("",e.getMessage());
            }
        }

        //tab选中的监听事件
        tablayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(final TabLayout.Tab tab) {

                holder = new ViewHolder(tab.getCustomView());
                holder.tvTabName.setSelected(true);
                holder.tvTabNumber.setSelected(true);
                //选中后字体变大
                holder.tvTabName.setTextSize(17);
                holder.tvTabNumber.setTextSize(11);
                //让Viewpager跟随TabLayout的标签切换

                viewpager.setCurrentItem(tab.getPosition());
                MinuteKillId=id.get(tab.getPosition());
//                if (tabNumbers.get(tab.getPosition()) == 0) {
//                    if (tabIstime.get(tab.getPosition()) == 1) {
//                       Contig.Isspceial=01;
//                    } else if (tabIstime.get(tab.getPosition()) == 0) {
//                        Isspceial=00;
//                    } else {
//                        Isspceial=01;
//                    }
//                } else if (tabNumbers.get(tab.getPosition()) == 1) {
//                    Isspceial=10;
//                } else if (tabNumbers.get(tab.getPosition()) == 2) {
//                    Isspceial=20;
//                }
                Log.e("数据",MinuteKillId);
                loadshoping(0, a, MinuteKillId,tabNumbers.get(tab.getPosition()));//,tabIstime.get(tab.getPosition())
                mylv_tablayout.setMode(PullToRefreshBase.Mode.BOTH);//两端刷新
                mylv_tablayout.setSelected(true);
                mylv_tablayout.setScrollingWhileRefreshingEnabled(true);
                mylv_tablayout.setOnRefreshListener(new PullToRefreshBase.OnRefreshListener2<ListView>() {
                    @Override
                    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {

                        loadshoping(0,a, MinuteKillId,tabNumbers.get(tab.getPosition()));

                    }

                    @Override
                    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {

                        loadshoping(0,a++, MinuteKillId,tabNumbers.get(tab.getPosition()));

                    }
                });
                new Handler(new Handler.Callback() {
                    @Override
                    public boolean handleMessage(Message msg) {
                        mylv_tablayout.setRefreshing(true);
                        return false;
                    }
                }).sendEmptyMessageDelayed(0, 200);
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {
                holder = new ViewHolder(tab.getCustomView());
                holder.tvTabName.setSelected(false);
                holder.tvTabNumber.setSelected(false);
                //恢复为默认字体大小
                holder.tvTabName.setTextSize(17);
                holder.tvTabNumber.setTextSize(11);
            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    int length =5;
    int start=0;
    private void loadshoping(final int downorup, int starts, String minuteKillId, final Integer isspecial) {
        if (downorup == 0) {
            length=5;
            start=0;
        } else if (downorup == 1) {
            length=5;
            start=starts;
        }
        Log.e("特卖商品",ApiManager.ZT_SPECIAL_SPECIALLIST+"?specialId="+minuteKillId+"&type="+Contig.typex);
        OkHttpUtils.get().url(ApiManager.ZT_SPECIAL_SPECIALLIST+"?specialId="+minuteKillId+"&type="+Contig.typex+"&start="+start+"&length="+length).build().execute(new StringCallback() {
            @Override
            public void onError(Request request, Exception e) {

            }

            @Override
            public void onResponse(String response) {
                mylv_tablayout.onRefreshComplete();
                Gson gson = new Gson();
                listshop = gson.fromJson(response,Minutekillshop.class);
                if(listshop.getCode().equals("10000")) {


                    if (listshop.getData().getList() != null && listshop.getData().getList().size() > 0) {
//                        tv_no_message.setVisibility(View.GONE);
                        mylv_tablayout.setVisibility(View.VISIBLE);
                    } else {
                        if (start == 0) {
                            Log.e("数据", "首页数据---------" + listshop.getData().getList());
//                            tv_no_message.setVisibility(View.VISIBLE);
                            mylv_tablayout.setVisibility(View.GONE);
                        } else {
//                            tv_no_message.setVisibility(View.GONE);
                            mylv_tablayout.setVisibility(View.VISIBLE);
                        }
                    }


                    if (listshop.getData().getList() != null && listshop.getData().getList().size() > 0) {

                        if (downorup == 0) {

//                            tv_no_message.setVisibility(View.GONE);
                            mylv_tablayout.setVisibility(View.VISIBLE);
                            listb = listshop.getData().getList();
                            adapterlv=new TabLayoutFragmentListviewAdapter(MinuteKillActivity.this,listshop.getData().getList(),isspecial);
                            mylv_tablayout.setAdapter(adapterlv);

                        } else {
//                            tv_no_message.setVisibility(View.GONE);
                            mylv_tablayout.setVisibility(View.VISIBLE);
                            listb.addAll(listshop.getData().getList());
                            if (listb.size() == 0) {
                                mylv_tablayout.setVisibility(View.GONE);
//                                tv_no_message.setVisibility(View.VISIBLE);
                            }
                            adapterlv.notifyDataSetChanged();
                            // listView.getRefreshableView().setSelection(a);
                        }
                    }
                }else{
                    Toast.makeText(MinuteKillActivity.this,listshop.getMsg(),Toast.LENGTH_SHORT).show();
                }
            }


        });

    }

    class ViewHolder {
        TextView tvTabName;
        TextView tvTabNumber;

        public ViewHolder(View tabView) {
            tvTabName = (TextView) tabView.findViewById(R.id.tv_tab_name);
            tvTabNumber = (TextView) tabView.findViewById(R.id.tv_tab_number);
        }
    }

    class TabAdapter extends FragmentPagerAdapter {

        private List<Fragment> fragments;


        public TabAdapter(FragmentManager fm, List<Fragment> fragments) {
            super(fm);
            this.fragments = fragments;
        }


        @Override
        public Fragment getItem(int position) {
            return fragments.get(position);
        }

        @Override
        public int getCount() {
            return fragments.size();
        }

        //设置tablayout标题
        @Override
        public CharSequence getPageTitle(int position) {
            return tabs1.get(position);
        }

    }
}


